package com.peacock.feather.utility;

import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

/**
 * bean工具类<br>
 * 对spring的BeanUtils类进行扩展
 * 
 * @author 项硕
 */
public class XBeanUtils {

	/**
	 * 获取参数clazz的属性列表
	 * @param clazz
	 * @return
	 */
	public static PropertyDescriptor[] getPropertyDescriptorList(Class<?> clazz) {
		Assert.notNull(clazz, "clazz must not be null");
		/* Arrays.asList方法返回的是java.util.Arrays.ArrayList.ArrayList,是一个内部类,没有实现add、remove等方法，因此需再次封装 */
		List<PropertyDescriptor> list = new ArrayList<PropertyDescriptor>(
				Arrays.asList(BeanUtils.getPropertyDescriptors(clazz)));
		for (PropertyDescriptor p : list) {
			/* 去除从Object继承的属性“class”, 虽然只有“getClass()”方法，但仍被解析为“PropertyDescriptor” */
			if ("class".equals(p.getName())) {
				list.remove(p);
				break;
			}
		}
		return list.toArray(new PropertyDescriptor[list.size()]);
	}

	/* ---------------------------------------- test ---------------------------------------- */
	
	@Test
	public void testGetPropertyDescriptorList() {
		Student stu = new Student();
		PropertyDescriptor[] arr = XBeanUtils.getPropertyDescriptorList(Student.class);
		for (PropertyDescriptor p : arr) {
			String name = p.getName();	// 属性名
			System.out.println("属性名：" + name);
			
			Method getter = p.getReadMethod();	// get方法
			Method setter = p.getWriteMethod();	// set方法
			
			if ("name".equals(name)) {
				try {
					setter.invoke(stu, "项硕");
					System.out.println(getter.invoke(stu));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public class Student implements Serializable {

		private static final long serialVersionUID = -5209893009620757334L;

		private Long id;
		
		private String name;
		
		private Date graduationTime;

		public Long getId() {
			return id;
		}

		public void setId(Long id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public Date getGraduationTime() {
			return graduationTime;
		}

		public void setGraduationTime(Date graduationTime) {
			this.graduationTime = graduationTime;
		}
		
	}
}
